package web.com.IcsUtile;/**
 * @Description
 * @author shine
 * 创建时间2022/8/5 14:48
 */

import lombok.extern.slf4j.Slf4j;
import net.fortuna.ical4j.data.CalendarOutputter;
import net.fortuna.ical4j.model.*;
import net.fortuna.ical4j.model.component.VAlarm;
import net.fortuna.ical4j.model.component.VEvent;
import net.fortuna.ical4j.model.component.VTimeZone;
import net.fortuna.ical4j.model.parameter.Cn;
import net.fortuna.ical4j.model.parameter.Role;
import net.fortuna.ical4j.model.parameter.XParameter;
import net.fortuna.ical4j.model.property.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;
import web.com.entity.vo.MeetingVo;

import javax.activation.DataHandler;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URI;

/**
 *@Description
 *@author shine
 *创建时间2022/8/5 14:48
 */
@Slf4j
@Component
public class IcsMail {

    @Autowired
    private JavaMailSenderImpl mailSender;



    public  void sendMeeting(MeetingVo meetingVo) {

        // 创建MIME消息准备发送邮件
        MimeMessage message = mailSender.createMimeMessage();
        try {

//            if (debug) {
//                meetingVo.setReciveAddr(debugReceiver);
//            }

            message.setFrom(new InternetAddress(meetingVo.getSendAddr()));
            // 发送给单人
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(meetingVo.getReciveAddr()));
            // 发送给多人
            /**
             * Message.RecipientType.TO 发送
             * Message.RecipientType.CC 抄送
             * Message.RecipientType.BCC 密送
             */
            //  message.addRecipients(Message.RecipientType.TO, new Address[]{new InternetAddress(toEmail),
            //                                new InternetAddress("aaa@126.com"),
            //                                new InternetAddress("bbb@126.com")});
            message.setSubject(meetingVo.getSubject());

            // 创建时间
            DateTime start = new DateTime(meetingVo.getStartTime());
            DateTime end = new DateTime(meetingVo.getEndTime());
            // 这里一定要注意，如果设置时间的utc 属性，发送的时间就会出现时间差
            start.setUtc(true);
            end.setUtc(true);
            // 创建事件
            VEvent meeting = new VEvent(start, end, meetingVo.getSubject());

            // 设置时区
            TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
            TimeZone timezone = registry.getTimeZone(meetingVo.getTimezone());
            // TimeZone timezone = registry.getTimeZone("UTC");
            VTimeZone tz = timezone.getVTimeZone();
            meeting.getProperties().add(tz.getTimeZoneId());
            // 设置地点
            meeting.getProperties().add(new Location(meetingVo.getLocation()));
            Uid uid = new Uid(meetingVo.getUid());
            meeting.getProperties().add(uid);

            // 组织者
            Organizer organizer = new Organizer(URI.create("mailto:" + meetingVo.getSendAddr()));
            organizer.getParameters().add(new Cn("会邀提醒"));
            meeting.getProperties().add(organizer);

            // 添加参与者
            Attendee attendee = new Attendee(URI.create("mailto:" + meetingVo.getReciveAddr()));
            attendee.getParameters().add(Role.OPT_PARTICIPANT);
            meeting.getProperties().add(attendee);

            // 添加主体
            meeting.getProperties().add(new Summary(meetingVo.getSubject()));
            ParameterList htmlParameters = new ParameterList();
            XParameter fmtTypeParameter = new XParameter("FMTTYPE", "text/html");
            htmlParameters.add(fmtTypeParameter);
            XProperty htmlProp = new XProperty("X-ALT-DESC", htmlParameters, meetingVo.getContent());
            // 添加邮件内容
            meeting.getProperties().add(htmlProp);

            // 提前15钟提醒
            VAlarm valarm = new VAlarm(new Dur(0, 0, -20, 0));

            // 提醒窗口显示的文字信息
            valarm.getProperties().add(new Summary("Event Alarm"));
            valarm.getProperties().add(Action.DISPLAY);
            valarm.getProperties().add(new Description(meetingVo.getSubject()));
            // 将VAlarm加入meeting
            meeting.getAlarms().add(valarm);

            // 创建日历
            Calendar icsCalendar = new Calendar();
            icsCalendar.getProperties().add(new ProdId("-//Events Calendar//iCal4j 1.0//EN"));
            icsCalendar.getProperties().add(Version.VERSION_2_0);
            icsCalendar.getProperties().add(Method.REQUEST);
            icsCalendar.getComponents().add(meeting);

            CalendarOutputter co = new CalendarOutputter(false);
            Writer wtr = new StringWriter();

            co.output(icsCalendar, wtr);

            String mailContent = wtr.toString();
            BodyPart messageBodyPart = new MimeBodyPart(); // 测试下来如果不这么转换的话，会以纯文本的形式发送过去
            messageBodyPart.setDataHandler(new DataHandler(
                    new ByteArrayDataSource(mailContent, "text/calendar;method=REQUEST;charset=\"UTF-8\"")));

            /** MimeMultipart 的构造方法默认 设置 subtype ="mixed"
             * multipart/mixed：附件。
             * multipart/related：内嵌资源。
             * multipart/alternative：纯文本与超文本共存
             */
            Multipart multipart = new MimeMultipart("alternative");
            multipart.addBodyPart(messageBodyPart);
            message.setContent(multipart);
            mailSender.send(message);

        } catch (Exception e) {
            e.printStackTrace();
            log.error("发送会邀出现异常：{}",e);
        }
    }


    public void cancelMeeting(MeetingVo meetingVo) {
        // 创建MIME消息准备发送邮件
        MimeMessage message = mailSender.createMimeMessage();
        try {

//            if (debug) {
//                meetingVo.setReciveAddr(debugReceiver);
//            }
            // message.setFrom(new InternetAddress(reminderSender));
            message.setFrom(new InternetAddress(meetingVo.getSendAddr()));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(meetingVo.getReciveAddr()));
            message.setSubject(meetingVo.getSubject());
            message.setText("测试邮件--测试");
            BodyPart messageBodyPart = new MimeBodyPart(); // 测试下来如果不这么转换的话，会以纯文本的形式发送过去

            // 创建时间
            DateTime start = new DateTime(meetingVo.getStartTime());
            DateTime end = new DateTime(meetingVo.getEndTime());
            start.setUtc(true);
            end.setUtc(true);
            // 创建事件
            VEvent meeting = new VEvent(start, end, meetingVo.getSubject());

            // 设置时区
            TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
            TimeZone timezone = registry.getTimeZone(meetingVo.getTimezone());
            VTimeZone tz = timezone.getVTimeZone();
            meeting.getProperties().add(tz.getTimeZoneId());
            // 设置地点
            meeting.getProperties().add(new Location(meetingVo.getLocation()));

            // 添加主体
            meeting.getProperties().add(new Summary(meetingVo.getSubject()));
            // 添加邮件内容
            meeting.getProperties().add(new Description(meetingVo.getContent()));

            Uid uid = new Uid(meetingVo.getUid());
            meeting.getProperties().add(uid);

            // 组织者
            Organizer organizer = new Organizer(URI.create("mailto:" + meetingVo.getSendAddr()));
            organizer.getParameters().add(new Cn("会邀取消"));
            meeting.getProperties().add(organizer);

            // 添加参与者
            Attendee attendee = new Attendee(URI.create("mailto:" + meetingVo.getReciveAddr()));
            attendee.getParameters().add(Role.OPT_PARTICIPANT);
            meeting.getProperties().add(attendee);

            // 创建日历
            Calendar icsCalendar = new Calendar();
            icsCalendar.getProperties().add(new ProdId("-//Events Calendar//iCal4j 1.0//EN"));
            icsCalendar.getProperties().add(Version.VERSION_2_0);
            icsCalendar.getProperties().add(Method.CANCEL);
            icsCalendar.getComponents().add(meeting);

            CalendarOutputter co = new CalendarOutputter(false);
            Writer wtr = new StringWriter();
            co.output(icsCalendar, wtr);
            String mailContent = wtr.toString();
            messageBodyPart.setDataHandler(new DataHandler(
                    new ByteArrayDataSource(mailContent, "text/calendar;method=REQUEST;charset=\"UTF-8\"")));

            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
            message.setContent(multipart);
            mailSender.send(message);

        } catch (Exception e) {
            e.printStackTrace();
            log.error("取消会邀发生异常：{}",e);
        }
    }

}
